package com.enjoychain.www.security.controller.business.accident;

import com.enjoychain.www.security.constant.BusinessTaskType;
import com.enjoychain.www.security.entity.task.TaskInfo;
import com.enjoychain.www.security.pojo.AccRelationPojo;
import com.enjoychain.www.security.service.IBasicFileService;
import com.enjoychain.www.security.service.ITaskInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Arrays;
import com.enjoychain.www.security.entity.accident.AccidentDetailItem;
import com.enjoychain.www.security.service.IAccidentDetailItemService;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ddmonk
 * @since 2023-01-29
 */
@Api(tags = "问题详情信息")
@RestController
@RequestMapping("/security/accidentDetailItem")
@Slf4j
public class AccidentDetailItemController {

    @Autowired
    IAccidentDetailItemService service;

    @Autowired
    ITaskInfoService taskInfoService;

    @Autowired
    IBasicFileService fileService;


    @PreAuthorize("@ss.hasPermi('accident:detail-item:list')")
    @GetMapping(path = "/list", produces = {"application/json"})
    @ApiOperation(value = "获取列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accId", value = "事件id",paramType = "query", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNo", value = "页码", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "pageSize", value = "页面记录条数", paramType = "query", dataType = "long")
    })
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response= AccidentDetailItem.class),
    })
    public AjaxResult list(
                            @RequestParam(name = "accId") String accId,
                            @RequestParam(name = "pageNo", defaultValue = "1") long pageNo,
                            @RequestParam(name = "pageSize",defaultValue = "10") long pageSize){
        IPage<AccidentDetailItem> entityIPage = new Page<>(pageNo, pageSize);
        QueryWrapper<AccidentDetailItem> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(accId)) {
            queryWrapper.eq("acc_id",accId);
        }
        queryWrapper.orderByDesc("create_time");
        service.page(entityIPage,queryWrapper);
        for (AccidentDetailItem item : entityIPage.getRecords()){
            item.setFileList(fileService.getListByTypeAndId(BusinessTaskType.ACCIDENT,item.getId()));
        }
        return AjaxResult.success("list-accident_detail_item",entityIPage);
    }

    @PreAuthorize("@ss.hasPermi('accident:detail-item:query')")
    @GetMapping(value = "{id}")
    @ApiOperation("获取详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "id",paramType = "path", dataType = "String")
    })
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = AccidentDetailItem.class)
    })
    public AjaxResult getAccidentDetailItemInfo(@PathVariable(value = "id", required = false) String id)
    {
        return AjaxResult.success("get-accident_detail_item",service.getItemDetail(id));
    }

//    @PreAuthorize("@ss.hasPermi('accident:detail-item:import')")
//    @ApiOperation("导入")
//    @Log(title = "", businessType = BusinessType.IMPORT)
//    @PostMapping("/importData")
//    public AjaxResult importData(MultipartFile file) throws Exception{
//        ExcelUtil<AccidentDetailItem> util = new ExcelUtil<AccidentDetailItem>(AccidentDetailItem.class);
//        List<AccidentDetailItem> infos = util.importExcel(file.getInputStream());
//        return service.saveOrUpdateBatch(infos)?AjaxResult.success("批量插入成功"):AjaxResult.error("批量插入失败");
//    }


//    @ApiOperation("导出模板下载")
//    @PostMapping("/importTemplate")
//    public void importTemplate(HttpServletResponse response){
//        ExcelUtil<AccidentDetailItem> util = new ExcelUtil<AccidentDetailItem>(AccidentDetailItem.class);
//        util.importTemplateExcel(response,"");
//    }

    @PreAuthorize("@ss.hasPermi('accident:detail-item:add')")
    @PostMapping(consumes = {"application/json"}, produces = {"application/json"})
    @ApiOperation("新增")
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = AccidentDetailItem.class),
    })
    @Log(title = "", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody AccidentDetailItem entity){

        return service.saveOrUpdateAndChangeStatus(entity)? AjaxResult.success("add-accident_detail_item",entity): AjaxResult.error("新增失败");
    }


    @PreAuthorize("@ss.hasPermi('accident:detail-item:update')")
    @PutMapping(consumes = {"application/json"}, produces = {"application/json"})
    @ApiOperation("修改")
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = AccidentDetailItem.class)
    })
    @Log(title = "", businessType = BusinessType.UPDATE)
    public AjaxResult update(@RequestBody AccidentDetailItem entity){
        String operate = "update-accident_detail_item";
        return service.saveOrUpdateAndChangeStatus(entity)?AjaxResult.success(operate,service.getById(entity.getId())) : AjaxResult.error("修改客户基础信息失败");
    }

    @PreAuthorize("@ss.hasPermi('accident:detail-item:delete')")
    @DeleteMapping(value = "{id}", produces = {"application/json"})
    @ApiOperation("删除")
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = AjaxResult.class),
    })
    @Log(title = "", businessType = BusinessType.DELETE)
    public AjaxResult delete(@PathVariable(value = "id", required = false) String id){
        String operate = "delete-accident_detail_item";
        String[] ids = id.split(",");
        return service.removeBatchByIds(Arrays.asList(ids))?AjaxResult.success(operate) : AjaxResult.error("修改失败");
    }

    @PreAuthorize("@ss.hasPermi('accident:detail-item:list')")
    @GetMapping(path = "/relation/list", produces = {"application/json"})
    @ApiOperation(value = "获取列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accId", value = "事件id",paramType = "query", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNo", value = "页码", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "pageSize", value = "页面记录条数", paramType = "query", dataType = "long")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response= AccidentDetailItem.class),
    })
    public AjaxResult relateTask(
            @RequestParam(name = "accId") String accId,
            @RequestParam(name = "pageNo", defaultValue = "1") long pageNo,
            @RequestParam(name = "pageSize",defaultValue = "10") long pageSize){
        Page<TaskInfo> entityIPage = new Page<>(pageNo, pageSize);
        IPage<TaskInfo> pages = taskInfoService.getPageByAccId(entityIPage,accId);
        return AjaxResult.success("list-accident_detail_item",pages);
    }


    @PreAuthorize("@ss.hasPermi('accident:detail-item:list')")
    @PostMapping(path = "/relation", produces = {"application/json"})
    @ApiOperation(value = "绑定业务列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accId", value = "事件id",paramType = "query", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNo", value = "页码", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "pageSize", value = "页面记录条数", paramType = "query", dataType = "long")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response= AccidentDetailItem.class),
    })
    public AjaxResult addRelationTask(@RequestBody AccRelationPojo pojo){
        try {
            return service.relateTaskByTaskId(pojo.getAccId(),pojo.getTaskId())?AjaxResult.success():AjaxResult.error();
        } catch (IOException e) {
            log.error("Bind Accident Error:", e);
            return AjaxResult.error();
        }
    }

    @PreAuthorize("@ss.hasPermi('accident:detail-item:list')")
    @DeleteMapping(path = "/relation/{id}", produces = {"application/json"})
    @ApiOperation(value = "绑定业务列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accId", value = "事件id",paramType = "query", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNo", value = "页码", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "pageSize", value = "页面记录条数", paramType = "query", dataType = "long")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response= AccidentDetailItem.class),
    })
    public AjaxResult delRelationTask(@PathVariable(value = "id", required = false) String id){
        return service.removeRelationTask(id)?AjaxResult.success():AjaxResult.error();
    }



}
